// 客户端计算
#include <iostream>
#include <ctime>
#include "protocal.hpp"
#include "Socket.hpp"
#include <unistd.h>
using namespace std;
void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " ip prot[1024]+\n"
              << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    Sock sock;
    sock.Socket();
    bool r = sock.Connect(serverip, serverport);
    if (!r)
    {
        return 1;
    }

    const string oper = "+-*%/";

    srand(time(NULL));
    int cnt = 1;
    while (cnt <= 10)
    {
        int x = rand() % 100 + 1;
        usleep(1000);
        int y = rand() % 100;
        usleep(1000);
        char op = oper[rand() % oper.size()];

        request req(x, y, op);
        string in_message;
        req.Serialize(in_message);
        in_message = Encode(in_message);
        // cout << in_message << endl;

        int n = write(sock.Fd(), in_message.c_str(), in_message.size());

        char buffer[1024];
        std::string inbuffer_stream;

        int s = read(sock.Fd(), buffer, sizeof(buffer));

        string str;
        if (s > 0)
        {

            buffer[s] = 0;
            inbuffer_stream += buffer;
            std::cout << inbuffer_stream << std::endl;

            response req;
            bool rr = Decode(inbuffer_stream, str);
            if (!rr)
                break;
            req.Deserialize(str);
            cout << "result: " << req.result_ << " code: " << req.code_ << endl;
        }
        if (s <= 0)
        {
            cout << "客户端读取失败" << endl;
        }
        cnt++;
        sleep(1);
    }
    sock.Close();
    return 0;
}
